<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<label for="username"></label>
<input id="username" placeholder="请输入用户名" type="text">
<div>
    <input id="connect" type="button" value="连接服务器">
    <input disabled="disabled" id="disconnect" type="button" value="断开连接">
</div>
<div id="chat">

</div>

<div>
    <label for="content">请输入聊天内容</label>

    <input id="content" placeholder="聊天内容" type="text">
</div>
<button id="send">发送</button>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.5.1/sockjs.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.js"></script>
<script>
    var stompClient
    $(function () {
        console.log(this)
        $("#connect").click(() => {
            console.log(this)
            connect()
        })

        $("#send").click(() => {
            sendWebMsg()
        })

        $("#disconnect").click(() => {
            disConnected()
        })
    })

    function sendWebMsg() {
        console.log("发送消息")
        // arg0 : 发送消息的地址
        // arg1 : header
        // arg2 : 消息内容 注意发送的Json字符串key 要和 服务端接受的实体属性保持一致
        // send(destination,headers,body)
        stompClient.send("/app/hello", {}, JSON.stringify({
            'fromSb': $("#username").val(),
            'content': $("#content").val()
        }))
    }


    // 连接事件
    function connect() {
        if (!$("#username").val()) {
            alert("请输入用户名")
            return;
        }
        // 第一次和服务端建立连接,还是需要借助http连接,来表示把http连接升级成WebSocket连接
        let sockJS = new SockJS("/chat");
        stompClient = Stomp.over(sockJS);
        // client.connect(headers, connectCallback, errorCallback);
        stompClient.connect({}, (res) => {
            alert("连接成功")
            setConnected(true)
            // client.subscribe("/queue/test", message_callback, headers);
            stompClient.subscribe("/topic/greetings", (res) => {
                console.log(res);
                let content = res.body;
                let jsonContent = JSON.parse(content);
                $("#chat").append(`<div>来自的${jsonContent.fromSb}消息: ${jsonContent.content}</div>`)
            });
        })
    }

    // 断开连接
    function disConnected() {
        console.log("断开连接")
        setConnected(false)
    }

    /**
     *
     * @param connected boolean
     */
    function setConnected(connected) {
        $("#connect").attr("disabled", connected);
        $("#disconnect").attr("disabled", !connected);
        $("#send").attr("disabled", !connected);
    }
</script>
</html>